/**
 * Created by tdzl2003 on 9/10/16.
 */

import React, { PropTypes } from 'react';
import {Modal, Button, Form, Input, Alert} from 'antd';

export default class LoginModal extends React.Component {
  state = {
    isSubmitting: false,
    error: null,
  };
  submit = async () => {
    if (this.state.isSubmitting) {
      return;
    }
    this.setState({
      isSubmitting: true,
      error: null,
    });
    const {form, onSubmit ,dismiss} = this.props;
    try {
      const values = await new Promise((resolve, reject) => form.validateFields((err, values) => {
        err ? reject(Object.assign(new Error('ValidationError'), {reason: err})) : resolve(values);
      }));

      if (onSubmit) {
        await onSubmit(values);
      }

      form.resetFields();
      dismiss();
    } catch(err) {
      this.setState({
        error: err.message,
      })
    } finally {
      this.setState({isSubmitting: false});
    }
  };
  render() {
    const { form, dismiss, children, title, okTitle, ...others } = this.props;
    const { isSubmitting, error } = this.state;
    return (
      <Modal
        title={title}
        footer={[
          <Button key="back" type="ghost" size="large" onClick={dismiss}>
            取 消
          </Button>,
          <Button key="submit" type="primary" size="large" onClick={this.submit} loading={isSubmitting}>
            {okTitle}
          </Button>,
        ]}
        onCancel={dismiss}
        {...others}
      >
        <Form
          onSubmit={this.submit}
        >
          {error && <Alert message={error} type="error" showIcon/>}
          {children}
        </Form>
      </Modal>
    );
  }
}
